package com.roger.myHome.service.impl;


import com.roger.myHome.domain.DataEntity;
import com.roger.myHome.mapper.DataMapper;
import com.roger.myHome.service.DataService;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Service
public class DataServiceImpl implements DataService {
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Resource
    private DataMapper dataMapper;

    @Override
    public void batchInsertData(List<DataEntity> dataList) {
        // 分批插入数据
        int batchSize = 2500;  // 每批插入的数量

        List<Future<?>> futures = new ArrayList<>();

        for (int i = 0; i < dataList.size(); i += batchSize) {
            List<DataEntity> subList = dataList.subList(i, Math.min(i + batchSize, dataList.size()));
            futures.add(taskExecutor.submit(new Callable<Void>() {
                @Override
                public Void call() {
                    dataMapper.insertBatchSomeColumn(subList);
                    return null;
                }
            }));
        }

        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

}
